#!/sbin/openrc-run

extra_started_commands="reload"

: ${user:="pgbouncer"}
: ${group:="postgresql"}
: ${cfgfile:="/etc/pgbouncer/pgbouncer.ini"}
: ${nice_timeout:=60}
: ${force_quit:="no"}
: ${force_quit_timeout:=2}

name="PgBouncer"
command="/usr/bin/pgbouncer"
command_args="-q $cfgfile"
command_background="yes"

pidfile="/run/$RC_SVCNAME.pid"
start_stop_daemon_args="
	--user $user
	--group $group"

required_files="$cfgfile"

depend() {
	use net
	after postgresql
}

start_pre() {
	local socket_dir=$(get_config unix_socket_dir)
	if [ -n "$socket_dir" ]; then
		checkpath -d -m 0755 -o postgres:postgres "$socket_dir" || return 1
	fi

	local logfile="$(get_config logfile)"
	if [ -n "$logfile" ]; then
		checkpath -f -m 0640 -o $user:$group "$logfile" || return 1
	fi
}

stop() {
	local retry="SIGINT/$nice_timeout"
	yesno "$force_quit" \
		&& retry="$retry/SIGTERM/$force_quit_timeout" \
		|| force_quit_timeout=0

	local seconds=$(( $nice_timeout + $force_quit_timeout ))

	ebegin "Stopping $seconds (this can take up to $seconds seconds)"

	start-stop-daemon --stop \
		--pidfile "$pidfile" \
		--retry "$retry" \
		--progress \
		--exec "$command"
	eend $?
}

restart() {
	local socket_dir=$(get_config unix_socket_dir)

	if [ -n "$socket_dir" ]; then
		ebegin "Performing online restart of $name"
		"$command" -R "$command_args"
		eend $?
	else
		stop && start
	fi
}

reload() {
	ebegin "Reloading $name configuration"
	start-stop-daemon --signal HUP --pidfile "$pidfile"
	eend $?
}

get_config() {
	local name="$1"
	local default="${2:-}"

	if [ ! -f "$conffile" ]; then
		printf '%s\n' "$default"
		return 1
	fi
	sed -En "/^\s*${name}\b/{                      # find line starting with the name
		  s/^\s*${name}\s*=?\s*([^#]+).*/\1/;  # capture the value
		  s/\s*$//;                            # trim trailing whitespaces
		  s/^['\"](.*)['\"]$/\1/;              # remove delimiting quotes
		  p
		}" "$conffile" \
		| grep . || printf '%s\n' "$default"
}
